package com.example.web.controller;

import com.example.web.entity.Result;
import com.example.web.entity.User;
import com.example.web.entity.Customer;
import com.example.web.mapper.UserMapper;
import com.example.web.mapper.CustomerMapper;
import com.example.web.mapper.InteractionRecordMapper;
import com.example.web.utils.PasswordEncoder;
import com.example.web.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/debug")
@CrossOrigin(origins = "http://localhost:3001", allowCredentials = "true")
public class DebugController {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CustomerMapper customerMapper;
    
    @Autowired
    private InteractionRecordMapper interactionRecordMapper;
    
    @Autowired
    private PasswordEncoder md5PasswordEncoder;

    /**
     * 调试用户查询和密码验证
     */
    @GetMapping("/user/{username}")
    public Result<Object> debugUser(@PathVariable String username, @RequestParam String password) {
        try {
            // 1. 查询用户
            User user = userMapper.findByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 2. 获取数据库中的密码
            String dbPassword = user.getPassword();
            
            // 3. 验证密码
            boolean matches = md5PasswordEncoder.matches(password, dbPassword);
            
            // 4. 构造调试信息
            StringBuilder debugInfo = new StringBuilder();
            debugInfo.append("用户名: ").append(user.getUsername()).append("\n");
            debugInfo.append("用户ID: ").append(user.getId()).append("\n");
            debugInfo.append("用户状态: ").append(user.getStatus()).append("\n");
            debugInfo.append("数据库密码: ").append(dbPassword).append("\n");
            debugInfo.append("输入密码: ").append(password).append("\n");
            debugInfo.append("密码匹配: ").append(matches).append("\n");
            debugInfo.append("密码长度: ").append(dbPassword != null ? dbPassword.length() : 0).append("\n");
            debugInfo.append("是否MD5格式: ").append(dbPassword != null && dbPassword.length() == 32).append("\n");
            
            return Result.success(debugInfo.toString());
        } catch (Exception e) {
            return Result.error("调试失败: " + e.getMessage());
        }
    }
    
    /**
     * 生成新的加密密码
     */
    @GetMapping("/encode/{password}")
    public Result<String> encodePassword(@PathVariable String password) {
        try {
            String encoded = md5PasswordEncoder.encode(password);
            return Result.success("原密码: " + password + " -> 加密后: " + encoded);
        } catch (Exception e) {
            return Result.error("加密失败: " + e.getMessage());
        }
    }
}